'use strict'

const fs = require('fs')
const https = require('https')
const http = require('http')
const express = require('express')
const serveIndex = require('serve-index')
const socketIO = require('socket.io')

const app = express()

var options = {
	key: fs.readFileSync('./cert/1557605_www.learningrtc.cn.key'),
	cert: fs.readFileSync('./cert/1557605_www.learningrtc.cn.pem')
}

app.use(serveIndex('./public'))
app.use(express.static('./public'))


const PORT = 3000
// socket.id -> userId
const rooms = {}
// socket.id -> room num
const users = {}

// const server = https.createServer(options, app)
const server = http.createServer(app)
const io = socketIO.listen(server)

io.sockets.on("connection", socket => {

	socket.on("join", (room, userId) => {
		console.log(`${socket.id} join the room ${room}...`)
		const myRoom = io.sockets.adapter.rooms[room];
		if(myRoom) {
			// 防止重复加入
			if(myRoom[socket.id]) {
				return;
			}else {
				const peers = Object.keys(io.sockets.adapter.rooms[room].sockets)
				socket.emit("peers", peers)
			}
		}
		if(!rooms[room]) {
			rooms[room] = {}
		}
		// 加入房间
		socket.join(room)
		rooms[room][socket.id] = userId
		users[socket.id] = room
		// 给除自己外的所有人发送
		io.to(room).emit("userstatechange", rooms[room])
		console.log(`userstatechange:${JSON.stringify(rooms[room])}`)
	})

	socket.on("signal", (message, socketId) => {
		console.log(`${socket.id} send to ${socketId} signal: ${JSON.stringify(message)}`)
		if (socketId) {
			const client = io.sockets.connected[socketId]
			client && client.emit("signal", message, socket.id)
		} else {
			io.in(room).emit("signal", message, socket.id)
		}
	})

	socket.on("disconnecting", () => {
		const room = users[socket.id]
		if(!room) return;
		console.log(`${socket.id} disconnected ${room}...`)
		socket.leave(room)
		io.to(room).emit("leave", socket.id)
		// 移除属性
		if(socket && socket.id) {
			delete rooms[room][socket.id]
			delete users[socket.id]
		}
		// 给除自己外的所有人发送
		io.to(room).emit("userstatechange", rooms[room])
		console.log(`userstatechange:${JSON.stringify(rooms[room])}`)
	})


	socket.on("disconnect", () => {
		console.log(`${socket.id} disconnected room...`)
	})
})



server.listen(PORT, '0.0.0.0')

console.log(`server start at ${PORT}...`)